package com.mobile.collect.activitys;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.IdRes;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.mobile.collect.AddPointEvent;
import com.mobile.collect.R;
import com.mobile.collect.beans.DeviceInfo;
import com.mobile.collect.db.EntityManager;
import com.mobile.collect.dialogs.BottomListDialog;
import com.mobile.collect.dialogs.SubmitTipDialog;
import com.mobile.collect.dialogs.interfaces.OnDialogButtonClickListener;
import com.mobile.collect.dialogs.util.BaseDialog;
import com.mobile.collect.dialogs.v3.MessageDialog;
import com.mobile.collect.dialogs.v3.TipDialog;
import com.mobile.collect.fragments.DeviceFragment;
import com.mobile.collect.fragments.SettingFragment;
import com.mobile.collect.present.MainPresent;
import com.mobile.collect.utils.TimeUtil;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import cn.droidlover.xdroidmvp.base.BaseListActivity;
import cn.droidlover.xdroidmvp.base.BaseRecyclerAdapter;
import cn.droidlover.xdroidmvp.base.ListItemLongClickListener;
import cn.droidlover.xdroidmvp.base.RecyclerViewHolder;
import cn.droidlover.xdroidmvp.event.BusProvider;
import cn.droidlover.xdroidmvp.kit.NLog;
import cn.droidlover.xdroidmvp.mvp.XActivity;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Consumer;

public class MainActivity extends BaseListActivity<DeviceInfo, MainPresent> {

    @BindView(R.id.inputEt)
    EditText inputEt;
    @BindView(R.id.clearIv)
    ImageView clearIv;
    ImageView settingIv;
    TextView editDeviceName;
    TextView editDeviceNo;
    TextView createNameTv;
    RadioGroup mergeRg;

    @Override
    public void getIntentData() {

    }

    @Override
    public void initData(Bundle savedInstanceState) {
        super.initData(savedInstanceState);
        BusProvider.getBus().toObservable(AddPointEvent.class).observeOn(AndroidSchedulers.mainThread()).subscribe(new Consumer<AddPointEvent>() {
            @Override
            public void accept(AddPointEvent dataEvent) throws Exception {
                getP().getDeviceList(inputEt.getText().toString());
            }
        });
    }

    @Override
    public void initView() {
        super.initView();
        mRefreshLayout.setEnableRefresh(false);
        mRefreshLayout.setAutoLoadMore(false);
//        nodataView = boxEmptyTags;
        mBaseAdapter.setLongClickListener(new ListItemLongClickListener() {
            @Override
            public void itemLongClick(int position) {
                showBottomDialog(mBaseAdapter.getItemByPosition(position));
            }
        });

        inputEt.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                String text = inputEt.getText().toString();
                if (TextUtils.isEmpty(text)) {
                    clearIv.setVisibility(View.GONE);
                } else {
                    clearIv.setVisibility(View.VISIBLE);
                }
                getDataFromServer();
            }
        });

        clearIv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                inputEt.setText("");
            }
        });
        settingIv = findViewById(R.id.settingIv);
        settingIv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startActivity(new Intent(MainActivity.this,SettingActivity.class));
            }
        });

    }

    protected void showBottomDialog(final DeviceInfo deviceInfo) {
        List<String> list = new ArrayList<>();
        list.add("修改");
        list.add("删除");
        BottomListDialog bottomListDialog = new BottomListDialog(this, new BottomListDialog.BottomListSelectListener() {
            @Override
            public void itemClickCallback(String selectStr) {
                if (selectStr.equals("修改")) {
                    showAddDialog(deviceInfo);
                } else {
                    showDelTip(deviceInfo);
                }
            }
        });
        bottomListDialog.disPlay(list);
    }


    @Override
    public int getContentViewId() {
        return R.layout.activity_main;
    }

    @Override
    public MainPresent newP() {
        return new MainPresent();
    }


    public static void lunch(Context context) {
        context.startActivity(new Intent(context, MainActivity.class));
    }

    @Override
    public void onBackPressed() {
        Intent intent = new Intent(Intent.ACTION_MAIN);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.addCategory(Intent.CATEGORY_HOME);
        startActivity(intent);
    }


    @Override
    public int getTitleLayoutResId() {
        return 0;
    }


    @Override
    public boolean isNotWorkConnect() {
        return false;
    }

    @Override
    public BaseRecyclerAdapter<DeviceInfo> getAdapter() {
        return new BaseRecyclerAdapter<DeviceInfo>(this) {
            @Override
            public int getItemLayoutId(int viewType) {
                return R.layout.item_device;
            }

            @Override
            public void bindData(RecyclerViewHolder holder, final int position) {
                super.bindData(holder, position);
                final DeviceInfo info = getItemByPosition(position);
//                int count = getPointCount(info);
                holder.setText(R.id.deviceNameTv, info.getDeviceName() + "(" + info.getPointCount() + "点)");
                holder.setText(R.id.deviceNoTv, info.getDeviceNo());
            }
        };
    }

    @Override
    public void itemClick(int position) {
        DeviceInfo info = mBaseAdapter.getItemByPosition(position);
        DeviceUnitListActivity.lunch(this, info.getDeviceName(), info.get_ID());
    }


    @Override
    public void getDataFromServer() {
        getP().getDeviceList(inputEt.getText().toString());
    }


    private void showAddDialog(final DeviceInfo info) {

        MessageDialog.build(this)
                .setTitle("新建装置")
                .setMessage(null)
                .setCustomView(R.layout.dialog_device, new MessageDialog.OnBindView() {
                    @Override
                    public void onBind(MessageDialog dialog, View v) {
                        v.setLayoutParams(new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
                        editDeviceName = v.findViewById(R.id.edit_device_name);
                        editDeviceNo = v.findViewById(R.id.edit_device_no);
                        createNameTv = v.findViewById(R.id.createNameTv);
                        mergeRg = v.findViewById(R.id.mergeRg);
                        if (null != info) {
                            editDeviceName.setText(info.getDeviceName());
                            editDeviceNo.setText(info.getDeviceNo());
                            createNameTv.setText(info.getCreateUser());
                            if (info.isMerge()) {
                                mergeRg.check(R.id.yesRbt);
                            } else {
                                mergeRg.check(R.id.noRbt);
                            }
                        }

                    }
                })
                .setOkButton("完成", new OnDialogButtonClickListener() {
                    @Override
                    public boolean onClick(BaseDialog baseDialog, View v) {
                        String deviceName = editDeviceName.getText().toString().trim();
                        String deviceNo = editDeviceNo.getText().toString().trim();
                        String deviceCompany = createNameTv.getText().toString().trim();
                        return checkInputCount(info, deviceName, deviceNo, deviceCompany);

                    }
                })
                .setCancelButton("取消")
                .show();

    }


    private boolean checkInputCount(DeviceInfo info, String deviceName, String deviceNo, String createUser) {
        if (TextUtils.isEmpty(createUser)) {
            TipDialog.show(this, "建档人员不能为空", TipDialog.TYPE.WARNING);
            return true;
        }
        if (TextUtils.isEmpty(deviceName)) {
            TipDialog.show(this, "不能创建空装置名称", TipDialog.TYPE.WARNING);
            return true;
        }

        boolean isMerge;
        switch (mergeRg.getCheckedRadioButtonId()) {
            case R.id.yesRbt:
                isMerge = true;
                break;
            case R.id.noRbt:
                isMerge = false;
                break;
            default:
                TipDialog.show(this, "请选择是否合并", TipDialog.TYPE.WARNING);
                return true;
        }

        Long _id = -1l;
        if (info != null) {
            _id = info.get_ID();
        }
        long count = EntityManager.getInstance().queryDeviceInfoCount(_id, deviceName);
        if (count == 0) {
            save(info, deviceName, deviceNo, createUser, isMerge);
            return false;
        } else {
            TipDialog.show(this, "存在相同名称的装置", TipDialog.TYPE.WARNING);
            return true;
        }
    }


    private void save(DeviceInfo info, String deviceName, String deviceNo, String createUser, boolean isMerge) {
        String message;
        if (null == info) {
            info = new DeviceInfo();
            message = "添加成功";
        } else {
            message = "修改成功";
        }
        info.setDeviceName(deviceName);
        info.setDeviceNo(deviceNo);
        info.setCreateUser(createUser);
        info.setCreateTime(TimeUtil.getNowTimeStampAccuracySecond());
        info.setEditTime(TimeUtil.getNowTimeStampAccuracySecond());
        info.setMerge(isMerge);
        Long _id = EntityManager.getInstance().saveDeviceInfo(info);
        info.set_ID(_id);
        TipDialog.show(this, message, TipDialog.TYPE.WARNING);
        getP().getDeviceList("");
    }

    private void showDelTip(final DeviceInfo deviceInfo) {
        SubmitTipDialog submitTipDialog = new SubmitTipDialog(this, new SubmitTipDialog.SlectClickListener() {
            @Override
            public void submitClick() {
                EntityManager.getInstance().delDeviceInfo(deviceInfo);
                getP().getDeviceList("");
            }

            @Override
            public void cancelClick() {

            }
        });
        submitTipDialog.display("温馨提示", "是否删除 " + deviceInfo.getDeviceName() + "?", "取消", "删除");
    }

    @OnClick(R.id.addIv)
    public void onViewClicked() {
        showAddDialog(null);
    }
}
